package com.xcj.juhe.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcj.juhe.dto.RoleDataDto;
import com.xcj.juhe.dto.RoleDto;
import com.xcj.juhe.mapper.test1.ChannelMapper;
import com.xcj.juhe.mapper.test1.UserDataMapper;
import com.xcj.juhe.mapper.test1.UserMapper;
import com.xcj.juhe.service.RoleService;
import com.xcj.juhe.tool.MyTool;
import com.xcj.juhe.tool.SignSortTool;
import com.xcj.juhe.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xcj
 * @date 2021/4/15 14:20
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    String URL = "http://test-api.gamedachen.com/data/submit";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public ChannelMapper channelMapper;

    @Autowired
    public UserDataMapper userDataMapper;

    MyTool myTool = new MyTool();

    @Override
    public ResultVO addRole(RoleDto role) {

        String timeStr = myTool.StringToTime(role.getTime());

        ResultVO resultVO = new ResultVO();
        ArrayList list = new ArrayList();

        int sum = 0;

        String appId = role.getAppId();
        String channelId = role.getChannelId();
        String sdkId = channelMapper.selectSdkIdByAppIdAndChannelId(appId, channelId);

        for (int i = 0 ; i < role.getUserId().size() ; i++){

            HashMap map = new HashMap();
            map.put("appId",appId);
            map.put("channelId",channelId);
            map.put("deviceId",role.getDeviceId());
//            map.put("gameCoin","");
            map.put("opType",3);
            map.put("osType",0);
//            map.put("partyId","无");
//            map.put("partyMasterId","会长id");
//            map.put("partyMasterName","会长名称");
//            map.put("partyName","公会名称");
//            map.put("payAmount",0);
//            map.put("power","战力");
//            map.put("professionId","职业id");
//            map.put("professionName","职业名称");
            map.put("sdkId",sdkId);
            String userId = role.getUserId().get(i);
            map.put("userId",userId);
            String roleId = "role_"+role.getServerId()+"_"+userId;
            RoleDataDto roleDataByUserId = userDataMapper.findRoleDataByUserId(channelId,userId,role.getServerId(),roleId);
            if(roleDataByUserId != null){
                //已存在就升级

                roleId = roleDataByUserId.getRoleId();
                map.put("roleId",roleId);
                map.put("roleLevel",roleDataByUserId.getRoleLevel()+1);
                map.put("roleName",roleDataByUserId.getRoleName());

                map.put("serverId",roleDataByUserId.getServerId());
                map.put("serverName",roleDataByUserId.getServerName());

            }else {

                map.put("roleId",roleId);
                map.put("roleLevel",2);
                map.put("roleName","name_"+userId);
                map.put("serverId",role.getServerId());
                map.put("serverName","server_"+role.getServerId());
            }

//            map.put("subChannelId",0);
//            map.put("vipLevel",0);
//            String userName = userMapper.selectUserNameByUserId(userId);
//            map.put("userName",userName);
//
//            if (userName == null || "".equals(userName)){
//                log.info("无效的用户id,查无对应用户名！！！");
//                continue;
//            }else {

            //创角时间在用户注册时间之后
            if (Integer.parseInt(timeStr) > Integer.parseInt(userMapper.selectUserRegTimeByUserId(userId))){
                //上报角色数据
                if (this.callSubmit(map, role.getAppKey(),timeStr)){
                    list.add(roleId);
                    sum ++;
                }
            }else {
                log.error("角色创建时间必须在账号注册时间之后");
                resultVO.setCode(101);
                resultVO.setMsg("角色创建时间必须在用户id:"+userId+"的注册时间之后");
                resultVO.setData(0);
                return resultVO;
            }

//            }
        }

        if (sum > 0){
            resultVO.setCode(200);
            resultVO.setMsg("成功");
            Map resultMap = new HashMap();
            resultMap.put("successNumber",sum);
            resultMap.put("roleIdList",list);
            resultVO.setData(resultMap);
        }else {
            resultVO.setCode(100);
            resultVO.setMsg("都创角失败");
            resultVO.setData(0);
        }
        return resultVO;
    }

    //调用创角
    private Boolean callSubmit(Map map, String appkey, String timeStr) {

        if (map.get("sign") != null) {
            map.remove("sign");
        }

        //生成签名
        String linkString = SignSortTool.createLinkString(map, true, false);
        String signString = linkString + appkey;
        log.info("signString:{}", signString);
        String md5Str = DigestUtils.md5DigestAsHex(signString.getBytes());

        map.put("sign", md5Str);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(map, headers);
        log.info("请求参数：{}",request.getBody());

        ResponseEntity<String> entity = restTemplate.postForEntity(URL, request, String.class);

        String body = entity.getBody();

        log.info("{}上报了，接口相应：{}", map.get("userId"), body);

        JSONObject json = JSON.parseObject(body);
        String code = json.getString("code");

        if (code.equals("200")) {
            //非当天的时间，更新角色注册时间
            if (!myTool.isNowDay2(timeStr)){
                int i = userDataMapper.updateUserDateCTimeByCidAndUidAndSidAndRid(timeStr, map.get("channelId").toString(),
                        map.get("userId").toString(), map.get("serverId").toString(), map.get("roleId").toString());
                if (i > 0){
                    log.info("更新用户id:{}创角时间为：{}成功。",map.get("userId").toString(),timeStr);
                    return true;
                }else {
                    log.error("更新用户id:{}创角时间为：{}失败！！！",map.get("userId").toString(),timeStr);
                    return false;
                }
            }else {
                return true;
            }

        } else {
            log.error("创角失败:{}", body);
            return false;
        }

    }


}
